﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Entities;
using Business;
using DevComponents.DotNetBar;
using System.Text.RegularExpressions;
namespace Presentation
{
    public partial class frmQuanLyKhachHang : DevComponents.DotNetBar.Office2007Form
    {
        DataView dv = new DataView();
        DataTable dt = new DataTable();
        public frmQuanLyKhachHang()
        {
            InitializeComponent();
            dgvKhachHang.AutoGenerateColumns = false;
        }

        private void frmQuanLyKhachHang_Load(object sender, EventArgs e)
        {
            LoadGridView();
        }
        private void LoadGridView()
        {
            dt = KhachHangService.GetKhachHangTable(); ;
            dt.TableName = "KhachHang";
            dt.AcceptChanges();
            dv.Table = dt;
            dgvKhachHang.DataSource = dt;
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvKhachHang_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.RowIndex == dgvKhachHang.RowCount - 1)
                return;
            if (e.FormattedValue.ToString() == "")
            {
                MessageBoxEx.Show("Không được bỏ trống!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
            if (dgvKhachHang.Columns[e.ColumnIndex].Name == "DienThoai")
            {
                long sdt = 0;
                if (!long.TryParse(e.FormattedValue.ToString(), out sdt))
                {
                    MessageBoxEx.Show("Số điện thoại phải là số!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }
            }
            if (dgvKhachHang.Columns[e.ColumnIndex].Name == "Email")
            {
                string email = e.FormattedValue.ToString();
                string pattern = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|" +
               @"0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z]" +
               @"[a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$";
                System.Text.RegularExpressions.Match match = Regex.Match(email.Trim(), pattern, RegexOptions.IgnoreCase);

                if (!match.Success)
                {
                    MessageBoxEx.Show("Nhập email không đúng định dạng!", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    e.Cancel = true;
                }

            }
        }

        private int GetID()
        {
            dv.RowStateFilter = DataViewRowState.Added;
            DataTable dtThem = dv.ToTable();

            int id = -1;
            if (dtThem.Rows.Count == 0)
            {
                id = KhachHangService.GetCurrentID();

            }
            else
            {
                id = (int)dtThem.Rows[dtThem.Rows.Count - 1]["MaKhachHang"];

            }
            return id + 1;
        }
        private void dgvKhachHang_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            int id = GetID();
            for (int i = e.Row.Index - 1; i < dgvKhachHang.RowCount - 1; i++)
            {
                dgvKhachHang["MaKhachHang", i].Value = id++;
                dgvKhachHang["TienNo", i].Value = 0;
            }
        }

        private void dgvKhachHang_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (e.RowIndex == dgvKhachHang.RowCount - 1)
                return;
            for (int i = 0; i < dgvKhachHang.ColumnCount; i++)
            {
                if (dgvKhachHang[i, e.RowIndex].EditedFormattedValue.ToString() == "")
                {
                    dgvKhachHang.CurrentCell = dgvKhachHang[i, e.RowIndex];
                    dgvKhachHang.CurrentCell.Style.BackColor = Color.Red;
                    dgvKhachHang.CurrentCell.Style.ForeColor = Color.White;
                    dgvKhachHang.BeginEdit(true);
                    e.Cancel = true;
                    return;
                }
            }
        }

        private void dgvKhachHang_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            dgvKhachHang[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.White;
            dgvKhachHang[e.ColumnIndex, e.RowIndex].Style.ForeColor = Color.Black;
        }

        private void dgvKhachHang_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            int maKhachHang = int.Parse(e.Row.Cells["MaKhachHang"].FormattedValue.ToString());
            if (maKhachHang > KhachHangService.GetCurrentID())
            {
                for (int i = e.Row.Index + 1; i < dgvKhachHang.RowCount; i++)
                {
                    dgvKhachHang["MaKhachHang", i].Value = maKhachHang++;
                }

            }
        }

        private bool CapNhat()
        {
            dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
            DataTable dtCapNhat = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.Added;
            DataTable dtThem = dv.ToTable();

            dv.RowStateFilter = DataViewRowState.Deleted;
            DataTable dtXoa = dv.ToTable();
            if (dtCapNhat.Rows.Count == 0 && dtThem.Rows.Count == 0 && dtXoa.Rows.Count == 0)
            {
                MessageBoxEx.Show("Không có gì để cập nhật!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            for (int i = 0; i < dtThem.Rows.Count; i++)
            {
                KhachHangDTO kh = new KhachHangDTO();
                kh.MaKhachHang = (int)dtThem.Rows[i]["MaKhachHang"];
                kh.HoTen = dtThem.Rows[i]["HoTen"].ToString();
                kh.DiaChi = dtThem.Rows[i]["DiaChi"].ToString();
                kh.DienThoai = dtThem.Rows[i]["DienThoai"].ToString();
                kh.Email = dtThem.Rows[i]["Email"].ToString();
                kh.TienNo = 0;
                kh.TinhTrang = 1;
                KhachHangService.Insert(kh);
            }

            for (int i = 0; i < dtXoa.Rows.Count; i++)
            {
                int maKhachHang = (int)dtXoa.Rows[i]["MaKhachHang"];
                KhachHangService.Delete(maKhachHang);
            }

            for (int i = 0; i < dtCapNhat.Rows.Count; i++)
            {
                KhachHangDTO kh = new KhachHangDTO();
                kh.MaKhachHang = (int)dtCapNhat.Rows[i]["MaKhachHang"];
                kh.HoTen = dtCapNhat.Rows[i]["HoTen"].ToString();
                kh.DiaChi = dtCapNhat.Rows[i]["DiaChi"].ToString();
                kh.DienThoai = dtCapNhat.Rows[i]["DienThoai"].ToString();
                kh.Email = dtCapNhat.Rows[i]["Email"].ToString();
                kh.TienNo = 0;
                kh.TinhTrang = 1;
                KhachHangService.Update(kh);
            }

            MessageBoxEx.Show("Cập nhật thành công!", "Thông báo!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return true;
        }

        private void btnCapNhat_Click(object sender, EventArgs e)
        {
            CapNhat();
        }

        private void frmQuanLyKhachHang_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataTable table = dt.GetChanges();
            if (table != null && table.Rows.Count > 0)
            {
               
                    dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
                    DataTable dtCapNhat = dv.ToTable();

                    dv.RowStateFilter = DataViewRowState.Added;
                    DataTable dtThem = dv.ToTable();

                    dv.RowStateFilter = DataViewRowState.Deleted;
                    DataTable dtXoa = dv.ToTable();
                    if (dtCapNhat.Rows.Count != 0 || dtThem.Rows.Count != 0 || dtXoa.Rows.Count != 0)
                    {
                        DialogResult save = MessageBoxEx.Show("Bạn có muốn lưu?", "Thông báo!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                        if (save == DialogResult.Yes)
                        {
                            CapNhat();
                        }
                        if (save == DialogResult.Cancel)
                            e.Cancel = true;


                    }
               
               

            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            DialogResult rs = MessageBoxEx.Show("Bạn có muốn load lại dữ liệu?", "Thông báo!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (rs == DialogResult.Yes)
            {
                LoadGridView();
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
           
            if (dgvKhachHang.CurrentRow!=null && dgvKhachHang.CurrentRow.Index >= 0)
            {
                this.dgvKhachHang.Rows.RemoveAt(dgvKhachHang.CurrentRow.Index);
            }
        }
    }
}